/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.juick.mod;

import com.juick.mod.api.JuickMessage;

import android.app.Activity;
import android.content.Context;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.ForegroundColorSpan;
import android.text.style.StyleSpan;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.RelativeLayout.LayoutParams;

import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.json.JSONArray;

/**
 *
 * @author ugnich
 */
public class JuickMessagesAdapter extends ArrayAdapter<JuickMessage> {

    public static Pattern urlPattern = Pattern.compile("(ht|f)tps?://[a-z0-9\\-\\.]+[a-z]{2,}/?[^\\s\\n]*", Pattern.CASE_INSENSITIVE);
    public static Pattern msgPattern = Pattern.compile("#[0-9]{3,7}");
    public static Pattern unamePattern = Pattern.compile("@[a-z0-9-]*[^\\s\\n\\.,:\\)]*", Pattern.CASE_INSENSITIVE);
    public static Pattern boldPattern = Pattern.compile("\\*.+\\*"); 
    public static Pattern italicPattern = Pattern.compile("((?<=\\A)|(?<=\\s))/.+/");
    public static Pattern underlinePattern = Pattern.compile("_.+_");
    
    private String Replies;
    private final ImageDownloader imageDownloader = new ImageDownloader();
    
    Activity activity;

    public JuickMessagesAdapter(Context context) {
        super(context, R.layout.listitem_juickmessage);
        Replies = context.getResources().getString(R.string.Replies_) + " ";
    }

    public int parseJSON(String jsonStr) {
        try {
            JSONArray json = new JSONArray(jsonStr);
            int cnt = json.length();
            for (int i = 0; i < cnt; i++) {
                add(JuickMessage.parseJSON(json.getJSONObject(i)));
            }
            return cnt;
        } catch (Exception e) {
            Log.e("initOpinionsAdapter", e.toString());
        }
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View v = convertView;
        if (v == null) {
            LayoutInflater vi = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            v = vi.inflate(R.layout.listitem_juickmessage, null);
        }

        JuickMessage jmsg = getItem(position);
                
        RelativeLayout rl = (RelativeLayout) v.findViewById(R.id.listItemRelativeLayout);
        rl.setBackgroundColor(MainActivity.backgroundColor);

        TextView t = (TextView) v.findViewById(R.id.text);
        t.setBackgroundColor(MainActivity.msgBackgroundColor);
        t.setTextColor(MainActivity.textColor);
        t.setTextSize(MainActivity.textSize);
        t.setPadding(MainActivity.textPadding, 2, MainActivity.textPadding, 2);
        
        TextView info = (TextView) v.findViewById(R.id.infotext);
        info.setBackgroundColor(MainActivity.infoBackgroundColor);
        info.setTextColor(MainActivity.infoTextColor);
        info.setTextSize(MainActivity.textSize - 2);
        
        if (MainActivity.loadAvatar) {
        	int size = MainActivity.avatarSize;
        	ImageView av = (ImageView) v.findViewById(R.id.av);
        	av.setMaxHeight(size);
        	av.setMaxWidth(size);
        	av.setMinimumHeight(size);
        	av.setMinimumWidth(size);
       		imageDownloader.download("http://i.juick.com/as/" + jmsg.User.UID + ".png", (ImageView) av);
        	
        	LayoutParams tLayout = (LayoutParams) t.getLayoutParams();
        	tLayout.leftMargin = size + 4;
        	LayoutParams infoLayout = (LayoutParams) info.getLayoutParams();
        	infoLayout.leftMargin = size + 4;
        	t.setLayoutParams(tLayout);
        	info.setLayoutParams(infoLayout);
        }
        
        if (MainActivity.round) {
        	ImageView upLeft = (ImageView) v.findViewById(R.id.ul);
            upLeft.setImageResource(MainActivity.ulResId);
            
            ImageView upRight = (ImageView) v.findViewById(R.id.ur);
            upRight.setImageResource(MainActivity.urResId);
            
            ImageView downLeft = (ImageView) v.findViewById(R.id.dl);
            downLeft.setImageResource(MainActivity.dlResId);
            
            ImageView downRight = (ImageView) v.findViewById(R.id.dr);
            downRight.setImageResource(MainActivity.drResId);
        }
        
        String replies = null;
        
        if (jmsg.User != null && jmsg.Text != null) {
            
        	if (jmsg.replies > 0) {
                replies = Replies + jmsg.replies + "  ";
            }
        	
            SpannableStringBuilder ssb = new SpannableStringBuilder();
            String name = '@' + jmsg.User.UName;
            String tags = jmsg.getTags();
            ssb.append(name + ' ' + tags + "\n" + jmsg.Text);
            ssb.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), 0, name.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            ssb.setSpan(new ForegroundColorSpan(MainActivity.headerTextColor), 0, name.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            ssb.setSpan(new ForegroundColorSpan(MainActivity.headerTextColor), name.length() + 1, name.length() + tags.length() + 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

            int paddingt = name.length() + 1 + tags.length() + 1;
            int pos = 0;
            Matcher msgMatcher = msgPattern.matcher(jmsg.Text);
            while (msgMatcher.find(pos)) {
                ssb.setSpan(new ForegroundColorSpan(MainActivity.linkTextColor), paddingt + msgMatcher.start(), paddingt + msgMatcher.end(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                pos = msgMatcher.end();
            }
            
            pos = 0;
            Matcher unameMatcher = unamePattern.matcher(jmsg.Text);
            while (unameMatcher.find(pos)) {
                ssb.setSpan(new ForegroundColorSpan(MainActivity.unameTextColor), paddingt + unameMatcher.start(), paddingt + unameMatcher.end(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                pos = unameMatcher.end();
            }
            
            pos = 0;
            Matcher boldMatcher = boldPattern.matcher(jmsg.Text);
            while (boldMatcher.find(pos)) {
            	ssb.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), paddingt + boldMatcher.start(), paddingt + boldMatcher.end(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                pos = boldMatcher.end();
            }
            
            pos = 0;
            Matcher italicMatcher = italicPattern.matcher(jmsg.Text);
            while (italicMatcher.find(pos)) {
            	ssb.setSpan(new StyleSpan(android.graphics.Typeface.ITALIC), paddingt + italicMatcher.start(), paddingt + italicMatcher.end(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                pos = italicMatcher.end();
            }
            
            pos = 0;
            Matcher urlMatcher = urlPattern.matcher(jmsg.Text);
            while (urlMatcher.find(pos)) {
                ssb.setSpan(new ForegroundColorSpan(MainActivity.linkTextColor), paddingt + urlMatcher.start(), paddingt + urlMatcher.end(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                ssb.setSpan(new StyleSpan(android.graphics.Typeface.NORMAL), paddingt + urlMatcher.start(), paddingt + urlMatcher.end(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                pos = urlMatcher.end();
            }
            
            /*
            pos = 0;
            Matcher underlineMatcher = underlinePattern.matcher(jmsg.Text);
            while (underlineMatcher.find(pos)) {
            	ssb.setSpan(new ForegroundColorSpan(0xFF000000), paddingt + underlineMatcher.start(), paddingt + underlineMatcher.end(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                pos = underlineMatcher.end();
            }
            */
            
            t.setText(ssb);
            info.setText(replies);
        } else {
            t.setText("");
        }
        return v;
    }
}
